package arithmetic;



//稀疏数组
public  class SparseArray {
    public static void main(String[] args) {

        int[][] arr = new int[11][11];
        arr[1][2] = 1;
        arr[2][3] = 2;
        arr[4][7] = 6;
        int sum = 0;
        for (int i = 0; i <arr.length ; i++) {
            for (int j = 0; j <arr[i].length ; j++) {
                if (arr[i][j]!=0){
                    sum++;
                }
                System.out.print(arr[i][j]+"\t");
            }
            System.out.println();
        }
        System.out.println("======================================================================");
//        稀疏数组的第一行
        int [][] arr1 = new int[sum+1][3];
        arr1[0][0]=arr.length;
        arr1[0][1]=arr[0].length;
        arr1[0][2]=sum;
//        将非零的值放入稀疏数组
        int count = 0;
        for (int i = 0; i <arr.length ; i++) {
            for (int j = 0; j <arr[i].length ; j++) {
                if (arr[i][j]!=0){
                    count++;
                    arr1[count][0] = i;
                    arr1[count][1] = j;
                    arr1[count][2] = arr[i][j];
                }
            }
        }
        for (int i = 0; i <arr1.length ; i++) {
            for (int j = 0; j <arr1[i].length ; j++) {
                System.out.print(arr1[i][j]+"\t");
            }
            System.out.println();
        }
        System.out.println("======================================================================");
        //还原
        int[][] arr2 = new int[arr1[0][0]][arr1[0][1]];
        for (int i = 1; i <arr1.length-1 ; i++) {
                arr2[arr1[count][0]][arr1[count][1]] = arr1[count][2];
        }
        for (int i = 0; i <arr2.length ; i++) {
            for (int j = 0; j <arr2[i].length ; j++) {

                System.out.print(arr[i][j]+"\t");
            }
            System.out.println();
        }


    }
    }




